//
//  FinancialViewController.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/15.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "FinancialViewController.h"
#import "IncomeCell.h"
#import "WithdrawalViewController.h"
#import "OrderManageControl.h"
#import "AccountViewController.h"
#import "myWkWebViewController.h"

@interface FinancialViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSDictionary *_todayData;
    UILabel *money ;
    UIButton *withdrawal;
}
@property(nonatomic, strong)UITableView *tableView;

@end

@implementation FinancialViewController

- (void)dealloc{
    NSLog(@"%@已经释放",[self class]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitle:@"财务管理" titleColor:[UIColor blackColor] font:font17];
    self.tableView.tableHeaderView = [self HeaderView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.backBtn setImage:[UIImage imageNamed:@"caiwu_nav_icon_default.png"] forState:UIControlStateNormal];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [self loadingData];
}

- (void)loadingData{
    __weak typeof(self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Finance/index" parameter:@{} successBlock:^(PPHttpRequest *request, id responseObj) {
        _todayData = responseObj;
        [weakself reloadViewData];
      
        [weakself removeExceptionView];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
      
       [weakself addExceptionAlView];
       [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}


- (void)buttonAction{
    __weak typeof(self)weakself = self;
    [weakself loadingData];
    
}

- (void)reloadViewData{
//    "getCash":{
//        "money": "2540.00",
//        "add_time": "1497451325",
//        "type": "3"
//    },
    NSString *str = @"";
    NSString *time = [ToolClass strToTime:_todayData[@"getCash"][@"add_time"] format:@"MM-dd"];
    if([_todayData[@"getCash"][@"type"] isEqualToString:@"1"]){
        str = [NSString stringWithFormat:@"%@已收入￥%@",time,_todayData[@"getCash"][@"money"]];
    }else if ([_todayData[@"getCash"][@"type"] isEqualToString:@"3"]){
        str = [NSString stringWithFormat:@"%@已提现￥%@",time,_todayData[@"getCash"][@"money"]];
    }else{
        str = [NSString stringWithFormat:@"%@平台服务费￥%@",time,_todayData[@"getCash"][@"money"]];
    }
    [withdrawal setTitle:str forState:UIControlStateNormal];
     money.text = [NSString stringWithFormat:@"￥%@",_todayData[@"cashBalance"]];
    
    [self.tableView reloadData];
}

- (UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //去掉分割线
       // _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"IncomeCell" bundle:nil] forCellReuseIdentifier:@"IncomeCell"];
        [self.view addSubview:_tableView];
        
    }
    //店铺管理，基本信息，店铺地图
    //系统 通知列表 关于我们
    return _tableView;
}


- (UIView *)HeaderView{
    UIView *heraderView = [[UIView alloc] init];
    heraderView.frame = CGRectMake(0, 0, SCREEN_W, GETHEIGHT(320));
    heraderView.backgroundColor = [UIColor whiteColor];
    
    UILabel *tip = [[UILabel alloc] init];
    tip.font = font14;
    tip.textColor = UIColorFromRGB(0x333333);
    tip.text = @"可提现余额";
    [heraderView addSubview:tip];
    tip.sd_layout.leftSpaceToView(heraderView, GETWITH(50))
    .topSpaceToView(heraderView, GETHEIGHT(56)).widthIs(GETHEIGHT(150))
    .autoHeightRatio(0);
    
    money = [[UILabel alloc] init];
    money.font = [UIFont fontWithName:@"Helvetica-Bold" size:GETHEIGHT(40)];
    money.text = [NSString stringWithFormat:@"￥0.00"];
    [heraderView addSubview:money];
    money.sd_layout.leftEqualToView(tip).topSpaceToView(tip, GETHEIGHT(24))
    .widthIs(0).autoHeightRatio(0);
    [money setSingleLineAutoResizeWithMaxWidth:GETWITH(400)];
    
    UIButton *reflect = [[UIButton alloc] init];
    [reflect setTitle:@"提现" forState:UIControlStateNormal];
    [reflect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    reflect.titleLabel.font = font14;
    reflect.layer.cornerRadius = 5;
    reflect.layer.masksToBounds = YES;
    [reflect setBackgroundColor:UIColorFromRGB(0xe71a41)];
    [reflect addTarget:self action:@selector(withdrawalBtn) forControlEvents:UIControlEventTouchUpInside];
    [heraderView addSubview:reflect];
    reflect.sd_layout.rightSpaceToView(heraderView, GETWITH(30)).centerYEqualToView(money)
    .widthIs(GETWITH(180)).heightIs(GETHEIGHT(70));
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor grayColor];
    [heraderView addSubview:view];
    view.sd_layout.topSpaceToView(money, GETHEIGHT(40))
    .leftSpaceToView(heraderView, 0).rightSpaceToView(heraderView, 0)
    .heightIs(GETHEIGHT(1));
    
    UIImageView *leftImge = [[UIImageView alloc] init];
    leftImge.image = [UIImage imageNamed:@"caiwu_icon5_default_nor.png"];
    [heraderView addSubview:leftImge];
    leftImge.sd_layout.leftSpaceToView(heraderView, GETWITH(50)).topSpaceToView(view, GETHEIGHT(40)).widthIs(GETWITH(36)).heightEqualToWidth();
    
    UILabel *jilu = [[UILabel alloc] init];
    jilu.font = font14;
    jilu.text = @"余额流水";
    [heraderView addSubview:jilu];
    jilu.sd_layout.leftSpaceToView(leftImge, GETWITH(20)).topSpaceToView(view, GETHEIGHT(40)).widthIs(GETWITH(150)).heightIs(GETHEIGHT(40));
    
    withdrawal = [[UIButton alloc] init];
    [withdrawal setTitle:@"" forState:UIControlStateNormal];
    withdrawal.titleLabel.font = font12;
    [withdrawal setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [heraderView addSubview:withdrawal];
    withdrawal.sd_layout.rightSpaceToView(heraderView, GETWITH(80)).topEqualToView(jilu).widthIs(0).heightIs(GETHEIGHT(40));
    [withdrawal setupAutoSizeWithHorizontalPadding:0 buttonHeight:GETHEIGHT(40)];
    
    __weak typeof(self)weakself = self;
    [withdrawal handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        AccountViewController *vc = [[AccountViewController alloc] init];
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    
    UIImageView *rightImg = [[UIImageView alloc] init];
    rightImg.image = [UIImage imageNamed:@"caiwu_nav_icon2_default.png"];
    [heraderView addSubview:rightImg];
    rightImg.sd_layout.rightSpaceToView(heraderView, GETWITH(46)).centerYEqualToView(jilu).widthIs(GETWITH(10)).heightIs(GETHEIGHT(20));
    return heraderView;
}

- (void)withdrawalBtn{
    WithdrawalViewController *vc = [[WithdrawalViewController alloc] init];
    vc.moneyStr = _todayData[@"cashBalance"];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma  mark --UITableViewDataSource UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 2;
    }
    NSArray *data = _todayData[@"historyBill"];
    return data.count<1?0:data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        IncomeCell *cell = nil;
        if(cell==nil)
            cell = [tableView dequeueReusableCellWithIdentifier:@"IncomeCell" forIndexPath:indexPath];
        int number = [_todayData[@"income"][@"payOrder"][@"sum_order"] intValue] +  [_todayData[@"income"][@"goodsOrder"][@"sum_order"] intValue];
        cell.progressView.frame = CGRectMake(GETWITH(30), cell.order.bottom + 5, 0, 10);
        if(indexPath.row == 0){
            cell.separatorInset = UIEdgeInsetsMake(0, SCREEN_W, 0, 0);
            NSDictionary *data = _todayData[@"income"][@"payOrder"];
          
            cell.order.text = @"买单订单";
            cell.orderNumber.text = [NSString stringWithFormat:@"共%@笔",data[@"sum_order"]];
            cell.ordermoney.text = [NSString stringWithFormat:@"￥%@",data[@"sum_price"]];
            cell.progressView.backgroundColor = UIColorFromRGB(0x15c7d4);
            if(number>0){
                CGFloat w = [data[@"sum_order"] doubleValue]/number;
               cell.progressView.width = (w)*(SCREEN_W-GETWITH(50));
            }
            if([_todayData[@"income"][@"payOrder"][@"sum_order"] intValue]<1){
                cell.progressView.width = (SCREEN_W-GETWITH(50));
                cell.progressView.backgroundColor = UIColorFromRGB(0xEBEBEB);
            }
        }else if (indexPath.row == 1){
            NSDictionary *data = _todayData[@"income"][@"goodsOrder"];
            cell.order.text = @"商品订单";
            cell.orderNumber.text = [NSString stringWithFormat:@"共%@笔",data[@"sum_order"]];
            cell.ordermoney.text = [NSString stringWithFormat:@"￥%@",data[@"sum_price"]];
            cell.progressView.backgroundColor = UIColorFromRGB(0xf0ce12);
            if(number>0){
                CGFloat w = [data[@"sum_order"] doubleValue]/number;
                cell.progressView.width = (w)*(SCREEN_W-GETWITH(50));
            }
            if([_todayData[@"income"][@"goodsOrder"][@"sum_order"] intValue]<1){
                cell.progressView.width = SCREEN_W-GETWITH(50);
                cell.progressView.backgroundColor = UIColorFromRGB(0xEBEBEB);
            }
        }
        cell.progressView.layer.cornerRadius = 5;
        cell.progressView.layer.masksToBounds = YES;
        cell.left_constrat.constant = GETWITH(50);
        cell.right_Constrat.constant = GETWITH(30);
         cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        NSArray *data = _todayData[@"historyBill"];
        NSDictionary *dic = data[indexPath.row];
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(GETWITH(50), 10, 150, 30)];
        time.font = font14;
        time.text = dic[@"mounth_date"];
        [cell.contentView addSubview:time];
        
        UILabel *rightLab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_W-GETWITH(260), 10,GETWITH(200), 30)];
        rightLab.font = font14;
        rightLab.textAlignment = NSTextAlignmentRight;
        rightLab.text = [NSString stringWithFormat:@"￥%@",dic[@"sum_price"]];

        [cell addSubview:rightLab];
        if(indexPath.row == 0){
            cell.backgroundColor = UIColorFromRGB(0xffdbb9);
        }
         cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
   
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        NSArray *data = _todayData[@"historyBill"];
        NSDictionary *dic = data[indexPath.row];
        [self historyBillChart:dic[@"mounth_date"]];
    }else if(indexPath.section == 0){
        
        if(indexPath.row == 0){
            OrderManageControl *vc = [[OrderManageControl alloc] init];
            vc.index = 0;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            OrderManageControl *vc = [[OrderManageControl alloc] init];
            vc.index = 1;
            [self.navigationController pushViewController:vc animated:YES];

        }

       
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 55;
    }
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *bigView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
    bigView.backgroundColor = UIColorFromRGB(0xf5f5f5);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_W, 50)];
    view.backgroundColor = [UIColor whiteColor];
    [bigView addSubview:view];
    if(section==0){
        UILabel *tip = [[UILabel alloc] initWithFrame:CGRectMake(GETWITH(30), 10, 100, 30)];
        tip.text = @"今日收入";
        tip.textColor = UIColorFromRGB(0x666666);
        tip.width = [ToolClass heighW:[UIFont systemFontOfSize:17] titleStr:@"今日账单"].width;
        tip.font = [UIFont systemFontOfSize:17];
        [view addSubview:tip];
        
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(tip.right, 5, 100, 20)];
        time.centerY = tip.centerY;
        NSString *strtime = [TimeUtils ToTimeFormat:[NSDate date] TimeFormat:@"yyyy-MM-dd"];
        time.text = [NSString stringWithFormat:@"(%@)",strtime];
        time.font = [UIFont systemFontOfSize:12];
        [view addSubview:time];
        
        __weak typeof(self)weakself = self;
        UIButton *button = [[UIButton alloc] init];
        button.titleLabel.textColor = UIColorFromRGB(0x333333);
        button.titleLabel.font = font17;
        [button setBackgroundColor:[UIColor clearColor]];
        CGFloat number = [_todayData[@"income"][@"payOrder"][@"sum_price"] floatValue] +  [_todayData[@"income"][@"goodsOrder"][@"sum_price"] floatValue];
        NSString *titleWidth = [NSString stringWithFormat:@"￥%.2f",number];
        CGFloat width = [ToolClass heighW:font17 titleStr:titleWidth].width;
        button.frame = CGRectMake(SCREEN_W-width-GETWITH(70), 0, width, 50);
        
        [button setTitle:titleWidth forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [view addSubview:button];
        UIImageView *rightImg = [[UIImageView alloc] initWithFrame:CGRectMake(button.right+10, 0, 8, 15)];
        rightImg.centerY = button.centerY;
        rightImg.image = [UIImage imageNamed:@"caiwu_nav_icon2_default.png"];
        [view addSubview:rightImg];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:view.bounds];
        [btn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            OrderManageControl *vc = [[OrderManageControl alloc] init];
            [weakself.navigationController pushViewController:vc animated:YES];
        }];

        [view addSubview:btn];

    }else{
        UILabel *tip = [[UILabel alloc] initWithFrame:CGRectMake(GETWITH(30), 10, 100, 30)];
        tip.text = @"历史账单";
        tip.textColor = UIColorFromRGB(0x666666);
        tip.width = [ToolClass heighW:[UIFont systemFontOfSize:17] titleStr:@"今日账单"].width;
        tip.font = [UIFont systemFontOfSize:17];
        [view addSubview:tip];
        
        UIButton *button = [[UIButton alloc] init];
        [button setBackgroundColor:[UIColor clearColor]];
         CGFloat width = [ToolClass heighW:font14 titleStr:@"全部历史账单"].width;
         button.frame = CGRectMake(SCREEN_W-width-GETWITH(60), 0, width, 40);
        button.centerY = tip.centerY;
        button.hidden = YES;
        [button setTitle:@"全部历史账单" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = font14;
        [view addSubview:button];
        
        UIImageView *rightImg = [[UIImageView alloc] initWithFrame:CGRectMake(button.right+10, 0, 5, 10)];
        rightImg.centerY = button.centerY;
        rightImg.hidden = YES;
        rightImg.image = [UIImage imageNamed:@"caiwu_nav_icon2_default.png"];
        [view addSubview:rightImg];


    }
    return bigView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 1)];
    view.backgroundColor =  UIColorFromRGB(0xf5f5f5);
    return view;
}


- (void)historyBillChart:(NSString *)mounth_date{
    // /ShopApi/Finance/historyBillChart
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setObject:mounth_date forKey:@"mounth_date"];
    [dic setObject:[userDefaults objectForKey:@"admin_id"] forKey:@"admin_id"];
    [dic setObject:[userDefaults objectForKey:@"guid"] forKey:@"guid"];
    [dic setObject:[ToolClass getData] forKey:@"time"];
    NSString *token = [ToolClass gettoken:dic];
    [dic setObject:token forKey:@"authKey"];
    
    myWkWebViewController *vc = [[myWkWebViewController alloc] init];
    vc.myurl = [NSString stringWithFormat:@"%@/ShopApi/Finance/historyBillChart?admin_id=%@&guid=%@&time=%@&mounth_date=%@&authKey=%@",APP_HOST_ADDRESS,[userDefaults objectForKey:@"admin_id"],[userDefaults objectForKey:@"guid"],[ToolClass getData],mounth_date,token];
    vc.toTitle = @"账单图表";
    [self.navigationController pushViewController:vc animated:YES];
}

@end
